#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
from pypinyin import lazy_pinyin, Style

def chinese_to_pinyin(chinese_str):
    """将中文转换为拼音，使用下划线分隔"""
    # 使用pypinyin库将中文转换为拼音
    pinyin_list = lazy_pinyin(chinese_str, style=Style.NORMAL)
    # 将拼音列表连接成字符串，使用下划线分隔
    pinyin_str = '_'.join(pinyin_list)
    # 处理特殊字符，将非字母数字下划线的字符替换为下划线
    pinyin_str = re.sub(r'[^a-zA-Z0-9_]', '_', pinyin_str)
    # 将连续的下划线替换为单个下划线
    pinyin_str = re.sub(r'_+', '_', pinyin_str)
    # 去除开头和结尾的下划线
    pinyin_str = pinyin_str.strip('_')
    # 如果开头是数字，加上前缀
    if pinyin_str and pinyin_str[0].isdigit():
        pinyin_str = 'num_' + pinyin_str
    return pinyin_str.lower()

def parse_transition_meta(file_path):
    """解析transition_meta.py文件，提取转场效果信息"""
    transitions = []
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 使用正则表达式匹配转场效果定义
    # 匹配格式: 变量名 = Transition_meta("名称", is_vip, "resource_id", "effect_id", "md5", default_duration, is_overlap)
    pattern = r'(\w+)\s*=\s*Transition_meta\("([^"]+)",\s*(True|False),\s*"([^"]+)",\s*"([^"]+)",\s*"([^"]+)",\s*([0-9.]+),\s*(True|False)\)'
    
    matches = re.findall(pattern, content)
    
    for match in matches:
        var_name, name, is_vip, resource_id, effect_id, md5, default_duration, is_overlap = match
        transition = {
            'var_name': var_name,  # 原始变量名（中文）
            'java_var_name': chinese_to_pinyin(var_name),  # 转换为拼音的变量名
            'name': name,
            'is_vip': is_vip,
            'resource_id': resource_id,
            'effect_id': effect_id,
            'md5': md5,
            'default_duration': default_duration,
            'is_overlap': is_overlap
        }
        transitions.append(transition)
    
    return transitions

def generate_java_constants(transitions):
    """生成Java常量定义"""
    java_constants = []
    
    # 添加VIP转场和非VIP转场的注释分隔
    vip_transitions = [t for t in transitions if t['is_vip'] == 'True']
    non_vip_transitions = [t for t in transitions if t['is_vip'] == 'False']
    
    # 生成非VIP转场常量
    if non_vip_transitions:
        java_constants.append("    // 非VIP转场效果")
        for transition in non_vip_transitions:
            const = f'    public static final Transition {transition["java_var_name"]} = new Transition("{transition["name"]}", {transition["is_vip"].lower()}, "{transition["resource_id"]}", "{transition["effect_id"]}", "{transition["md5"]}", {transition["default_duration"]}, {transition["is_overlap"].lower()});'
            java_constants.append(const)
        java_constants.append("")
    
    # 生成VIP转场常量
    if vip_transitions:
        java_constants.append("    // VIP转场效果")
        for transition in vip_transitions:
            const = f'    public static final Transition {transition["java_var_name"]} = new Transition("{transition["name"]}", {transition["is_vip"].lower()}, "{transition["resource_id"]}", "{transition["effect_id"]}", "{transition["md5"]}", {transition["default_duration"]}, {transition["is_overlap"].lower()});'
            java_constants.append(const)
    
    return java_constants

def generate_java_file(transitions, output_path):
    """生成完整的Java文件"""
    java_constants = generate_java_constants(transitions)
    
    java_content = [
        "package com.cms.jy.draft.constant;",
        "",
        "import com.cms.jy.draft.entity.Transition;",
        "",
        "public class VideoTransitions {",
        "    // 转场效果常量"
    ]
    
    java_content.extend(java_constants)
    java_content.append("}")
    
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(java_content))

def main():
    # 输入和输出文件路径
    input_file = "src/main/java/com/cms/jy/draft/constant/transition_meta.py"
    output_file = "src/main/java/com/cms/jy/draft/constant/VideoTransitions.java"
    
    # 解析transition_meta.py文件
    transitions = parse_transition_meta(input_file)
    
    # 生成Java文件
    generate_java_file(transitions, output_file)
    
    print(f"成功转换 {len(transitions)} 个转场效果到 {output_file}")

if __name__ == "__main__":
    main()